<template>
	<div class="homepage" ref="homepage">
		<div class="backBtn" @click="back()" v-if="level != 1"></div>
		<div class="map" id="mapChartgo"></div>
	</div>
</template>

<script>
// import cityMap from '@/js/china-main-city-map.js';
import * as echarts from 'echarts';
import areaJson from '@/assets/area.json';
import axios from 'axios';
// import positionImg from '@/assets/img/position.png';
import Vue from 'vue';
// import registerAndsetOption from '@/js/echarts-map'
import { bigScreenApi } from '@/api/index';
//中国地图（第一级地图）的ID、Name、Json数据
var areaId = '331100';
var areaName = ' 丽水市';
// var areaJson = null;

//记录父级ID、Name
var mapStack = [];
var parentId = null;
var parentName = null;

//Echarts地图全局变量，主要是在返回上级地图的方法中会用到
var myChart = null;
function getRandomInt(min, max) {
	min = Math.ceil(min);
	max = Math.floor(max);
	return Math.floor(Math.random() * (max - min + 1)) + min;
}

export default {
	name: 'chinaMap',
	props: {
		msg: String,
	},
	data() {
		return {
			mapJson: {},
			chooseName: '',
			pointData: {},
			sum: {},
			mapData: {},
			cityMap: {},
			cityId: '',
			alltree: [],
			level: 1,
			center: [],
		};
	},
	// props: {
	// 	level: {
	// 		type: [String, Number],
	// 		default: 0,
	// 	},
	// },
	mounted() {
		this.mapChartgo();
		// console.log(areaJson);
	},
	methods: {
		/**
		 * 返回上一级地图
		 */
		back() {
			axios.get('/json/lishuimap/' + areaId + '.geojson', {}).then((response) => {
				const mapJson = response.data;
				console.log('mapJson', mapJson);
				this.mapJson = mapJson;
				parentId = areaId;
				parentName = '丽水市';
				this.chooseName = '丽水市';
				this.cityId = areaId;
				this.level = 1;
				this.center = [119.569458, 28.111077];
				this.registerAndsetOption(myChart);
			});
		},
		/**
		 * Echarts地图
		 */

		mapChartgo(divid) {
			let _this = this;
			axios.get('/json/lishuimap/' + areaId + '.geojson', {}).then((response) => {
				const mapJson = response.data;
				console.log('mapJson', mapJson);
				this.mapJson = mapJson;
				parentId = areaId;
				parentName = '丽水市';
				this.chooseName = '丽水市';
				this.cityId = areaId;
				this.level = 1;
				myChart = echarts.init(document.getElementById('mapChartgo'));
				// this.getMapData(myChart);
				this.center = [119.569458, 28.111077];
				this.registerAndsetOption(myChart);
				myChart.on('click', function (param) {
					console.log('触发了点击', param);
					if (
						param.componentSubType === 'scatter' ||
						(param.componentSubType === 'map' && param.data && param.data.value > 0)
					) {
						_this.chooseEarea(param);
					}
				});
			});
		},
		chooseEarea(param) {
			var cityId = this.cityMap[param.name].id;
			this.center = this.cityMap[param.name].center;
			console.log(cityId);
			if (cityId) {
				//代表有下级地图
				axios.get('/json/lishuimap/' + cityId + '.geojson', {}).then((response) => {
					const mapJson = response.data;
					this.mapJson = mapJson;
					this.chooseName = param.name;
					this.cityId = cityId;
					this.level = 2;
					this.registerAndsetOption(myChart);
					//this.getMapData(myChart, cityId, param.name, mapJson, true);
					// console.log(this.chooseName);
					// console.log(mapJson);
				});
			}
		},
		/**
		 *
		 * @param {*} myChart
		 * @param {*} id        省市县Id
		 * @param {*} name      省市县名称
		 * @param {*} mapJson   地图Json数据
		 * @param {*} flag      是否往mapStack里添加parentId，parentName
		 */
		registerAndsetOption(myChart, id, name, mapJson, flag) {
			if (flag) {
				//往mapStack里添加parentId，parentName,返回上一级使用
				mapStack.push({
					mapId: parentId,
					mapName: parentName,
				});
				parentId = id;
				parentName = name;
			}
			console.log('mapStack=================');
			// this.$emit('mapCheck', {
			// 	name: this.chooseName,
			// 	mapJson: this.pointData,
			// 	level: mapStack.length,
			// 	cityId: parentId,
			// });
			// console.log(name, parentName);
			echarts.registerMap('丽水市', this.mapJson);
			let { mapData, pointData, cityMap } = this.initMapData(this.mapJson);
			console.log('mapData', pointData);
			this.mapData = mapData;
			this.pointData = pointData;
			this.cityMap = cityMap;
			console.log('ss', this.pointData, cityMap);

			let options = {
				geo: {
					label: {
						normal: {
							show: true,
						},
						emphasis: {
							show: true,
						},
					},
					roam: true,
					opacity: 0,
					// zlevel: 1,
					map: '丽水市',
					// aspectScale: 0.75,
					zoom: 1,
					z: 1,
					scaleLimit: {
						min: 1,
						max: 3,
					},
					itemStyle: {
						normal: {
							areaColor: 'rgba(255,255,255,0)',
							shadowColor: 'rgba(255,255,255,0)',
							borderColor: 'rgba(255,255,255,0)',

							shadowOffsetX: 0,
							shadowOffsetY: 0,
						},

						// center: this.mapJson.features ? this.mapJson.features[0].properties.cp : [],
					},
					emphasis: {
						itemStyle: {
							areaColor: 'rgba(255,255,255,1)',
							shadowColor: 'rgba(255,255,255,0)',
							borderColor: 'rgba(255,255,255,0)',
						},
					},
					center: this.center,
				},
				visualMap: {
					min: 0,
					max: 1000,
					text: ['High', 'Low'],
					realtime: false,
					calculable: true,
					inRange: {
						color: ['#92bbf9', '#5193f4', '#3175da'],
					},
					show: false,
					textStyle: {
						color: '#fff',
					},
				},
				tooltip: {
					trigger: 'item',
					formatter: (p) => {
						// console.log(p);
						if (p.componentSubType == 'effectScatter') {
							let val = p.value instanceof Array ? p.value[2] : p.value;
							if (p.name == '南海诸岛') return;
							if (window.isNaN(val)) {
								val = 0;
							}
							// console.log(val, val.toFixed(2));
							let txtCon;
							if (val > 10000) {
								p.value instanceof Array
									? (txtCon =
											"<div style='text-align:left'>" +
											p.name +
											':<br />病人总数：' +
											val.toFixed(2) +
											'万人</div>')
									: null;
							} else {
								p.value instanceof Array
									? (txtCon =
											"<div style='text-align:left'>" +
											p.name +
											':<br />病人总数：' +
											val +
											'人</div>')
									: null;
							}
							return txtCon;
						}
					},
					hideDelay: 10,
				},
				series: [],
			};
			options.series.push(
				{
					type: 'map',
					map: '丽水市',
					roam: true,
					geoIndex: 0,
					aspectScale: 0.75, //长宽比
					selectedMode: false,
					zoom: 1,
					scaleLimit: {
						min: 1,
						max: 3,
					},

					// geoIndex: 0,
					zlevel: 11,
					// z: 2,
					showLegendSymbol: false,
					label: {
						// 通常状态下的样式
						normal: {
							show: true,
							textStyle: {
								color: '#fff',
							},
						},
						// 鼠标放上去的样式
						emphasis: {
							textStyle: {
								color: '#640000',
							},
						},
					},
					tooltip: {
						show: false,
						formatter: function (params) {
							// console.log(params);
							return null;
						},
					},
					itemStyle: {
						normal: {
							borderColor: '#58c3ff',
							borderWidth: 1.5,
							areaColor: '#c5dcfe',
						},
					},
					emphasis: {
						label: {
							show: false,
						},
						itemStyle: {
							areaColor: '#58c3ff',
						},
					},
					center: this.center,
					data: this.mapData,
				},
				{
					name: '散点',
					type: 'effectScatter',
					coordinateSystem: 'geo',
					zlevel: 12,
					data: this.pointData.slice(0, 3),
					symbol: 'image://' + require('@/assets/img/position.png'),
					symbolKeepAspect: true,
					// symbolSize: 8,
					symbolSize: [55, 80],
					showEffectOn: 'emphasis', //加载完毕显示特效
				}
			);
			console.log(options);
			myChart = echarts.init(document.getElementById('mapChartgo'));
			myChart.setOption(options, true);
		},
		initMapData(mapJson) {
			var mapData = [],
				pointData = [],
				cityMap = [];
			console.log('mapJson.features', mapJson.features.length);
			for (var i = 0; i < mapJson.features.length; i++) {
				let value = getRandomInt(20, 1000);
				let properties = mapJson.features[i].properties;
				let geometry = mapJson.features[i].geometry;
				mapData.push({
					name: properties.name,
					value: value,
				});
				pointData.push({
					name: properties.name,
					value: [
						properties.center ? properties.center[0] : geometry.coordinates[0][0][0][0],
						properties.center ? properties.center[1] : geometry.coordinates[0][0][0][1],
						value,
					],
				});
				cityMap[properties.name] = {
					id: properties.id,
					center: properties.center,
				};
			}

			return {
				mapData,
				pointData,
				cityMap,
			};
		},

		// 生成随机数据
		getMapData(myChart) {
			let pointData = {},
				mapJson = {},
				sum = {};
			this.mapJson.features.forEach((father) => {
				mapJson[this.timeTitle[i]].push({
					name: father.properties.name,
					value: getRandomInt(20, 1000),
					cityCode: father.id ? father.id : '',
				});
				pointData[this.timeTitle[i]].push({
					name: father.properties.name,
					value: [
						father.properties.cp
							? father.properties.cp[0]
							: this.getCenterPoint(father.properties.name)
							? this.getCenterPoint(father.properties.name)[0]
							: father.geometry.coordinates[0][0][0][0],
						father.properties.cp
							? father.properties.cp[1]
							: this.getCenterPoint(father.properties.name)
							? this.getCenterPoint(father.properties.name)[1]
							: father.geometry.coordinates[0][0][0][1],
						getRandomInt(20, 1000),
					],
					cityCode: father.id ? father.id : '',
				});
			});
			mapJson[this.timeTitle[i]] = mapJson[this.timeTitle[i]].sort(function (a, b) {
				return b.value - a.value;
			});
		},
		getCenterPoint(name) {
			let point = [];
			areaJson.forEach((item) => {
				if (item.name == name) {
					point = [item.lon, item.lat];
				}
			});
			return point;
		},
	},
};
</script>

<style scoped lang="less">
.homepage {
	height: 100%;
	// overflow: auto;
	height: 100%;
	position: relative;
}

.map {
	width: 100%;
	height: 100%;
	background: transparent;
}
.backBtn {
	position: absolute;
	top: 0;

	cursor: pointer;
	z-index: 99;

	width: 1.13rem;
	height: 0.36rem;
	position: absolute;
	top: 0.12rem;
	left: 0.07rem;
	background: url(/img/dashboard/back.png) no-repeat;
	background-size: cover;
	&:hover,
	&:active {
		background-image: url(/img/dashboard/back-active.png);
	}
}
</style>
